<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>预订房间</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="stylesheet" href="/css/font.css">
    <link rel="stylesheet" href="/css/xadmin.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="/js/xadmin.js"></script>
    <script type="text/javascript" src="/js/cookie.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .roomlist {
        margin-top: 20px;
        width: 20%;
        height: 100%;
        float: left;
    }

    .content {
        width: 79%;
        height: 100%;
        float: left;
    }

    .jiajian {
        width: 130px;
        height: 30px;
        margin: 0 auto;
        text-align: center;
        font-size: 14px;
    }

    .jiajian input {
        float: left;
        width: 60px;
        height: 27px;
        border: 1px solid #eee;
        outline: none;
        margin-left: -1px;
        line-height: 27px;
        text-align: center;
    }

    .jia, .jian {
        border: 1px solid #eee;
        float: left;
        width: 30px;
        height: 27px;
        line-height: 27px;
        cursor: pointer;

    }

    .jia {
        border-radius: 0 5px 5px 0;
        margin-left: -1px;
    }

    .jian {
        border-radius: 5px 0 0 5px;
    }

    .jia:hover, .jian:hover {
        background-color: rgba(0, 0, 0, 0.1);
    }

    #search {
        margin-bottom: 10px;
    }

    #search button, #search input {
        float: left;
    }

    #search input {
        width: 150px;
        height: 30px;
    }
</style>

<body>
<div class="roomlist">
    <h3>已预订的房间类型：</h3>
    <ul id="demo"></ul>
</div>
<div class="content">
    <table class="layui-table" id="r_table" lay-filter="test">
    </table>
    <div class="page">
        <div>
            <a class="prev" href="">&lt;&lt;</a>
            <a class="num" href="">1</a>
            <span class="current">2</span>
            <a class="num" href="">3</a>
            <a class="num" href="">489</a>
            <a class="next" href="">&gt;&gt;</a>
        </div>
    </div>
    <br>
    <form class="layui-form" id="update">
        <div class="layui-form-item">
            <input type="hidden" id="reserveId" name="reserveId">
            <div class="layui-inline">
                <label for="orderDate" class="layui-form-label">
                    入住时间
                </label>
                <div class="layui-input-inline">
                    <input class="layui-input" name="orderDate" id="orderDate" lay-verify="required" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline">
                <label for="leaveDate" class="layui-form-label">
                    退房时间
                </label>
                <div class="layui-input-inline">
                    <input class="layui-input" name="leaveDate" id="leaveDate" lay-verify="required" autocomplete="off">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label for="phone" class="layui-form-label">
                    联系方式
                </label>
                <div class="layui-input-inline">
                    <input type="tel" id="phone" name="phone" required="" lay-verify="required|number"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label for="cashPledge" class="layui-form-label">
                    押金
                </label>
                <div class="layui-input-inline">
                    <input type="number" class="layui-input" name="cashPledge" id="cashPledge" lay-verify="required|number" autocomplete="off">
                </div>
            </div>

        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label for="remark" class="layui-form-label">
                    备注
                </label>
                <div class="layui-input-inline">
                    <input type="text" id="remark" name="remark" required="" lay-verify="remark"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" lay-filter="add" lay-submit>
                    确定入住
                </button>
            </div>
        </div>

    </form>

</div>
<script>
    layui.use(['tree', 'table', 'laydate', 'form'], function () {
        var $ = layui.jquery;
        var form = layui.form,
            laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#reservationTime' //指定元素
        });
        laydate.render({
            elem: '#goTime' //指定元素
        });
        //自定义验证规则
        form.verify({
            //验证固定号码是否有误
            // roomTel: [/\d{3,4}[-]\d{7}/, "房间固定号码格式有误"]
        });
        var table = layui.table;
        var tableRender = {
            id: 'tableId'
            , elem: '#r_table'
            , height: 350
            , page: false //开启分页
            , toolbar: '#toolbarDemo'
            , data: []
            , cols: [
                [ //表头
                    {type: 'checkbox', width: "5%", fixed: 'left'}
                    , {field: 'roomType', title: '房间类型', width: '20%', align: 'center'}
                    , {field: 'name', title: '房号', width: '20%', align: 'center'}
                    , {field: 'liveNums', title: '入住人数', width: '25%', align: 'center', toolbar: '#edit'}
                    , {field: 'operate', title: '操作', toolbar: '#operate', width: '30%', align: 'center'}
                ]
            ]
            , done: function (res, curr, count) {
                table.on('tool(test)', function (obj) {
                    //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    var dex = 0;
                    //获得表格数组
                    var oldData = table.cache["tableId"];
                    oldData.forEach(function (item, index, array) {
                        if (item.name == data.name)
                        //获得数组下标
                            dex = index;
                    })
                    if (layEvent == 'del') { //删除
                        layer.confirm('确定删除吗？', function (index) {
                            if (dex)
                                oldData.splice(dex, 1);
                            table.reload('tableId', {
                                //删除指定项
                                data: oldData,
                                done: function (res, curr, count) {
                                    refreshCount(oldData);
                                }
                            })
                            layer.close(index);
                            //向服务端发送删除指令
                        });
                    } else if (layEvent == 'reduce') {
                        var result = $(this).parent().find('input');
                        var val = parseInt(result.val()) > 1 ? (parseInt(result.val()) - 1) : 1;
                        console.log(table.cache.tableId);
                        oldData[dex].liveNums = val;
                        table.reload('tableId', {
                            data: oldData,
                            done: function (res, curr, count) {
                                refreshCount(oldData);
                            }
                        });
                    } else if (layEvent == 'plus') {
                        var result = $(this).parent().find('input');
                        var setVal = parseInt(result.val()) + 1;
                        oldData[dex].liveNums = setVal;
                        table.reload('tableId', {
                            data: oldData,
                            done: function (res, curr, count) {
                                refreshCount(oldData);
                            }
                        });
                    }
                });
            }
        };
        var tableIns = table.render(tableRender);

        //更新数量
        function refreshCount(oldData) {
            var counts = $(".jiajian").find('input');
            for (var i = 0; i < counts.length; i++) {
                counts.eq(i).val(oldData[i].liveNums);
            }
        }

        table.on("toolbar(test)", function (obj) {
            console.log(obj);
            if (obj.event == 'delAll') {
                layer.confirm('确定删除吗？', function (index) {
                    table.reload('tableId', {
                        data: null
                    });
                    layer.close(index);
                })
            }
        });
        //生成菜单树结构
        //从父页面获得已预订房间类型菜单数据
        $.get({
            url: '/checkin/getRoomDetail',
            success: function (res) {
                //装预订信息，房间类型加预订数量
                var roomInfo = {};
                var roomList = parent.$('#valuestack').find('li');
                var roomType = [];
                $.each(roomList, function (index, ele) {
                    var father = {};
                    father.name = $(ele).text();
                    roomInfo[$(ele).text()] = $(ele).attr('orderNum');
                    // father.orderNum = $(ele).attr('orderNum');
                    for (var key in res) {
                        if (father.name == key) {
                            //生成指定类型的children对象数组
                            var child = [];
                            $.each(res[key], function (dex, elem) {
                                var obj = {};
                                obj.name = elem;
                                obj.roomType = key;
                                child.push(obj);
                            });
                            father.children = child;
                        }
                    }
                    roomType.push(father);
                });
                console.log('roomInfo', roomInfo);
                layui.tree({
                    elem: '#demo' //传入元素选择器
                    , nodes: roomType
                    , click: function (nodes) {
                        if (!nodes.children) {
                            var tableBak = table.cache["tableId"];
                            var flag = true;
                            //若表格无数据则开阀增添数据，如表格有数据则除重
                            if (tableBak) {
                                //判断是否已经添加该项
                                flag = tableBak.every(function (value, index, array) {
                                    return value.name != nodes["name"]
                                });
                                //判断是否已经超过预订数量
                                var orderNum = 0;
                                for (var key in roomInfo) {
                                    if (key == nodes.roomType) {
                                        $.each(tableBak, function (index, ele) {
                                            if (ele['roomType'] == key)
                                                orderNum++;//获得已经选择的某种类型的房间数量
                                        });
                                        console.log('key:', key);
                                        //    与预订数量进行比较，如果选择的房间已经等同预定数量，则不能添加
                                        if (roomInfo[key] == orderNum) {
                                            flag = false;
                                            layer.alert('房间数超过预订数量');
                                        }
                                    }
                                }
                            } else
                                tableBak = [];
                            if (flag) {
                                nodes.liveNums = 1;
                                tableBak.push(nodes);
                                table.reload("tableId", {
                                    data: tableBak,
                                    done: function (res, curr, count) {
                                        refreshCount(tableBak);
                                    }
                                });
                            }
                        }
                    }
                });

            }
        });
        form.on('submit(add)', function (data) {
            var dataF = data.field;
            //解析预订数据
            var dataR = table.cache.tableId;
            console.log('dataR', dataR);
            var result = true;
            var updateData = {};
            updateData["id"] = dataF["reserveId"];
            $.each(dataR, function (index, ele) {
                dataF.liveNums = ele.liveNums;
                dataF.rdid = ele.name;
                $.ajax({
                    url: '/checkin/addSave',
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(dataF),
                    success: function (res) {
                        if (res.status != 0) {
                            result = false;
                        } else {
                            //入住成功，修改入住状态-->预定完成
                            updateData["delStatus"] = "1";
                            console.log(updateData);
                            $.ajax({
                                url:'/reserve/editStatus',
                                type:'POST',
                                data:updateData,
                                success:function (res) {
                                    if (res.status==0){
                                        // layer.alert("入住成功", {icon: 6}, function () {
                                        //     // 获得frame索引
                                        //     var index = parent.layer.getFrameIndex(window.name);
                                        //     //关闭当前frame
                                        //     parent.layer.close(index);
                                        //     parent.location.reload();
                                        // });
                                        result = 0;
                                    } else {
                                        // layer.alert(res.msg, {icon: 5})
                                        result = 1;
                                    }
                                }
                            })

                        }

                    }
                })
            });
            if (result) {
                layer.alert("入住成功", {icon: 6}, function () {
                    // 获得frame索引
                    var index = parent.layer.getFrameIndex(window.name);
                    //关闭当前frame
                    parent.layer.close(index);
                    parent.location.reload();
                });
                //入住成功后删除之前订单
                // $.post("/reserve/remove", {'phone': dataF.phone}, function (res) {
                //     if (res.status == 0) {
                //         layer.alert("预订成功", {icon: 6}, function () {
                //             // 获得frame索引
                //             var index = parent.layer.getFrameIndex(window.name);
                //             //关闭当前frame
                //             parent.layer.close(index);
                //             parent.location.reload();
                //         });
                //     }
                //     else {
                //         layer.alert("删除失败", {icon: 1});
                //     }
                // });

            }
            else
                layer.alert(res.msg, {icon: 5});
        });

    })
    ;
</script>
<!--加减输入框-->
<script type="text/html" id="edit">
    <div class="jiajian">
        <span class="jian" lay-event="reduce">-</span>
        <input type="text" name="" value="1">
        <span class="jia" lay-event="plus">+</span>
    </div>
</script>
<script type="text/html" id="operate">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!--头部工具栏-->
<script type="text/html" id="toolbarDemo">
    <!--<div class="layui-btn-container">-->
        <!--<button class="layui-btn layui-btn-danger" lay-event="delAll"><i class="layui-icon"></i>批量删除</button>-->
    <!--</div>-->
</script>
</body>

</html>